var taskChange = null;
var isOperayion = 0;
Ext.define('cfWeb.controller.appManage.AppManageController', {
    extend: 'Ext.app.Controller',
    views: ['appManage.AppManageView',
        'templateManage.TemplateManageView',
        'appMonitor.AppMonitorView',
        'appManage.NewAppLoadTem',
        'appManage.NewAppDataStorage',
        'appManage.NewAppAnaLog',
        'appManage.ConfigOracle',
        'cfWeb.cfWebComponent.CfWindow',
        'cfWeb.cfWebComponent.CollapsibleBlock',
        'cfWeb.cfWebComponent.LbuttonIconListView',
        'cfWeb.cfWebComponent.CbuttonIconListView',
        'cfWeb.cfWebComponent.SlideLayer',
        'cfWeb.cfWebComponent.AppHeadView',
        'cfWeb.cfWebComponent.CfChartTypeI',
        'cfWeb.cfWebComponent.ButtonListView',
        'appManage.NewAppCfWindow',
        'appManage.AppListDetailsView',
        'cfWeb.cfWebComponent.CfPanelTypeI',
        'cfWeb.view.appManage.AppTemplateView',
        'cfWeb.view.appManage.AppTemplateDetailView',
        'cfWeb.cfWebComponent.ServiceConfigView',
        'log.LogFileWindow',
        'cfWeb.cfWebComponent.IconListViewTypeII',
        'cfWeb.cfWebComponent.ModuleConstructView',
        'cfWeb.cfWebComponent.VariableListView',
        'cfWeb.cfWebComponent.InstanceStatusView',
        'cfWeb.cfWebComponent.InstanceChartType',
        'cfWeb.cfWebComponent.ServiceDetail',
        'cfWeb.view.accountSetting.BuildpackManageView',
        'cfWeb.cfWebComponent.SwitchContentView',
        'cfWeb.view.appManage.NewBindServiceWindow',
        'cfWeb.view.dataStorage.NewDatabaseView',
        'cfWeb.view.dataStorage.DataStorageView',
        'cfWeb.cfWebComponent.CpuChartType',
        'cfWeb.view.log.LogAnalyWindow',
        'cfWeb.view.dataStorage.DataStorageDetailView',
        'appManage.AppUploadWindow',
        'appManage.RelatedAppView',
        'appManage.DefaultServiceView'
    ],
    stores: ['appManage.AppTemplateStore',
        'appManage.AppListStore',
        'appManage.DomainStore',
        'appManage.StorageStore',
        'appManage.StorageComboStore',
        'appManage.OrgStore',
        'log.LogFileStore',
        'appManage.SpaceStore',
        'appManage.ApplicationStore',
        'appManage.BuildpackStore',
        'appManage.DataAnalyseStore',
        'appManage.DataStorageStore',
        'appManage.TemplateOrgStore',
        'appManage.TemplateSpaceStore',
        'appManage.InstanceStateStore',
        'appManage.AppAccessStore',
        'appManage.AppDetailsEnvVarStore',
        'appManage.AppHistStore',
        'cfWeb.store.appManage.ServiceStore',
        'cfWeb.store.dataStorage.DatabaseTmpStore',
        'dataStorage.DatabaseServiceStore',
        'dataStorage.DatabaseServiceBrokerStore',
        'dataStorage.DatabaseBrokerPlanStore',
        'dataStorage.DatabaseServiceSelectStore'
    ],
    temStore: Ext.create('cfWeb.store.appManage.AppListStore'),
    envName: undefined,
    anaListserNameLength: undefined,
    stoListserNameLength: undefined,
    appListserNameLength: undefined,
    anaListserName: undefined,
    anaListserNameDis: undefined,
    stoListserName: undefined,
    appListserName: undefined,
    appListserNameDis: undefined,
    NewAppWindow: undefined,
    newAppDataStorageView: undefined,
    STATUS: {
        'stop': 'STOPED',
        'boot': 'STARTED',
        'reboot': 'STARTED'
    },
    init: function () {
        this.control({
            'defaultService': {
                onItemAdd: this.addDefaultService
            },
            'newBindServiceWindow': {
                onSubmit: this.bindService
            },
            'templateManageView collapsibleBlock': {
                onSearch: this.onsearch,
                onAdd: this.add,
                clearSearch: this.search
            },
            'appListDetailsView cfChartTypeI[itemId=access]': {
                render: this.cfChartTypeIRenderAccess
            },
            'appListDetailsView cfChartTypeI[itemId=hist]': {
                render: this.cfChartTypeIRenderHist
            },
            'appListDetailsView buttonListView': {
                buttonClick: this.getAppInfoForTime
            },
            'newAppLoadTem': {
                render: this.onNewAppLoadTemRender
            },
            'newAppAnaLog form checkboxgroup': {
                add: this.adaptHeight
            },
            'appListDetailsView serviceDetail ': {
                menuClick: this.cbuttonMenuClick,
                itemAdd: this.showSerBindWin,
                render: this.serviceLoad,
                appClick: this.serviceClicked
            },
            'templateManageView lbuttonIconListView': {
                menuClick: this.menuClick,
                itemAdd: this.itemAdd
            },
            'appMonitorView cbuttonIconListView': {
                render: this.renderApps,
                menuClick: this.cbuttonMenuClick,
                appClick: this.appClick
            },
            'appNewStartWindow button[action=next]': {
                click: this.appNewNext
            },
            'appUploadWindow button[action=updateAppWar]': {
                click: this.appUpdateWar
            },

            'appUploadWindow button[action=close]': {
                click: this.closeWin
            },

            'appNewEndWindow button[action=complete]': {
                click: this.appNewComplete
            },

            'logService form fieldset[itemId=pattern] button[itemId=buttonTest]': {
                click: this.patternTest
            },

            'newAppCfWindow': {
                onSubmit: this.submitForm,
                beforeNext: this.formValidate
            },
            'appTemplateView': {
                beforeNext: this.nextTemplateView,
                onSubmit: this.submitTemplateView
            },
            'appTemplateView iconListViewTypeII': {
                itemsClick: this.itemsClick,
                afterrender: this.load
            },
            'appHeadView': {
                onStatusChange: this.onStatusChange,
                onDomainChange: this.onDomainChange,
                relateClicked: this.startCompare
            },
            'appListDetailsView button[itemId=openLog]': {
                click: this.showLog
            },
            'logFileWindow': {
                render: this.logFwinRender
            },
            'logFileWindow form button[action=logfileSearch]': {
                click: this.logFileSearch
            },
            'logFileWindow grid actioncolumn': {
                click: this.downloadLogFile
            },
            'switchContentView': {
                change: this.updataGraph
                //             	boxready:this.updateChartData
            },
            'variableListView[itemId=appVarEnv]': {
                render: this.appVarEnvRender,
                itemDelete: this.appVarEnvDelete,
                itemAdd: this.appVarEnvAdd,
                itemUpdate: this.appVarEnvUpdate,
                heightAdj: this.vHeightAdj,
                resize: this.vHeightAdj,
                refresh: this.variAdj
            },
            'configOracle': {
                grow: this.heightAdj,
                shrink: this.heightAdj,
                onItemAdd: this.addDatabaseService
            },
            'newDatabaseView combobox[itemId=serviceName]': {
                change: this.serviceNameChange
            },
            'newDatabaseView': {
                onSubmit: this.createServices
            },
            'cbuttonIconListView[id=databaselist]': {
                menuClick: this.deleteDatabaseService
            },
            'cbuttonIconListView[id=dataserverlist]': {
                menuClick: this.deleteAppService
            },
            'appListDetailsView': {
                close: this.isRefresh
            },
            'appListDetailsView button[itemId=analyLog]': {
                click: this.openAnalyLog
            },
            //			'appListDetailsView relatedAppView':{
            //				beforedestroy:this.backToMain
            //			},
            'appListDetailsView relatedAppView thresholdControlView': {
                changeSubmit: this.changeInstance
            }
        });
    },
    changeInstance: function (me, data) {
        var appName = me.appName;
        console.log(appName);
        var thisName = me.up('relatedAppView').thisName;
        var num = data[0].value;
        Ext.Ajax.request({
            url: 'rest/app/scaleApp',
            method: 'POST',
            params: {
                autoScale: false,
                appName: appName,
                instanceNum: num
            },
            success: function (resp) {
                if (appName == thisName) {
                    me.up('appListDetailsView').down('thresholdControlView#detailThreshold').setMode('manual').items.items[0].setValue(num);
                }
                me.commitChange();
            },
            failure: function (response) {
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var obj = Ext.JSON.decode(response.responseText);
                if (obj.data != null && obj.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.AppExpandFailed);
                }
            }
        });
    },
    backToMain: function (me) {
        var item = me.up('appListDetailsView').down('container#detailContainer').items.items;
        for (var i = 0, l = item.length; i < l; i++) {
            item[i].show();
        }
    },
    startCompare: function (me, thisName, thatName, e) {
        if (!me.compare) {
            me.compare = true;
            var details = Ext.ComponentQuery.query('appListDetailsView')[0].down('container#detailContainer');
            for (var i = 0, l = details.items.items.length; i < l; i++) {
                details.items.items[i].hide();
            }
            var relatedAppView = Ext.widget('relatedAppView', {
                'thisName': thisName,
                'thatName': thatName
            });
            details.add(relatedAppView);
        } else {
            me.compare = false;
            var details = Ext.ComponentQuery.query('appListDetailsView')[0].down('container#detailContainer');
            for (var i = 0, l = details.items.items.length; i < l; i++) {
                details.items.items[i].show();
            }
            details.down('relatedAppView').destroy();
        }
    },
    closeWin: function (me) {
        me.up('window').close();
    },
    appUpdateWar: function (me) {
        var win = me.up('appUploadWindow');
        var appName = win.appName;
        win.down('hiddenfield[name=appName]').setValue(appName);
        var form = win.down('form');
        var file = form.down('filefield').getValue();
        var isGrayUpdate = win.down('checkbox').getValue();
        win.down('hiddenfield[name=isGrayUpdating]').setValue(isGrayUpdate);
        if (file == null || file == '') {
            return;
        }
        var appList = Ext.getCmp('temp');
        var appListStore = appList.getStore();
        var waitWindow = Ext.MessageBox.show({
            title: cfWebLang.Util.uploading,
            closable: false,
            cls: 'style-cfLoading'
        });
        form.submit({
            url: 'rest/app/update',
            method: 'POST',
            success: function () {
                win.close();
                waitWindow.close();
                appListStore.load();
            },
            failure: function (response) {
                win.close();
                waitWindow.close();
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Main.SessionOverdue, function () {
                        parent.location.href = '/cfWeb/login.html';
                    });
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var obj = Ext.JSON.decode(response.responseText);
                if (obj.data != null && obj.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                }
            }

        });
        //win.close();
    },
    serviceClicked: function (me, serName, index, e) {
        console.log(serName);
        var detailView = me.up('appListDetailsView');
        console.log(detailView.appName);
        var win = Ext.widget('dataStorageDetailView', {
            adaptTo: detailView
        });
        win.maskOnDisable = false;
        Ext.Ajax.request({
            url: 'rest/app/serviceDetails',
            method: 'GET',
            params: {
                appName: detailView.appName,
                serviceName: serName
            },
            success: function (res) {
                var obj = Ext.JSON.decode(res.responseText);
                var detailData = obj.data[0];
                console.log(detailData);
                if (detailData.serviceInstanceName.split('_')[0] == 'Oracle') {
                    win.slideUp();
                    var details = detailData.detail;
                    var credentials = details.credentials;
                    var data = {};
                    data.plan = details.plan;
                    data.label = detailData.service;
                    data.hostname = credentials.hostname;
                    data.port = credentials.port;
                    data.username = credentials.username;
                    data.password = credentials.password;
                    data.itemImg = detailData.serviceTypeImage;
                    data.title = detailData.serviceInstanceName;
                    data.databasename = credentials.databasename;
                    data.itemColor = '#f39851';
                    win.down('headView').updateAppStatus(data);
                } else if (detailData.serviceInstanceName.split('_')[0] == 'MySQL') {
                    win.slideUp();
                    var details = detailData.detail;
                    var credentials = details.credentials;
                    var data = {};
                    data.plan = details.plan;
                    data.label = detailData.service;
                    data.hostname = credentials.hostname;
                    data.port = credentials.port;
                    data.username = credentials.username;
                    data.password = credentials.password;
                    data.itemImg = detailData.serviceTypeImage;
                    data.title = detailData.serviceInstanceName;
                    data.databasename = credentials.databasename;
                    data.itemColor = '#55b0f6';
                    win.down('headView').updateAppStatus(data);
                } else {
                    win.close();

                }
            }
        });
    },
    deleteDatabaseService: function (me, act, id, e) {
        if (act == 'deleteService') {
            Ext.Ajax.request({
                url: 'rest/service/deleteinstance',
                method: 'POST',
                params: {
                    serviceName: id
                },
                success: function (response) {
                    me.getStore().load({
                        params: {
                            first: 1
                        }
                    });
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                    }
                    me.stopLoading(e + 1);
                }
            });
        }

    },
    vHeightAdj: function (me, arg) {
        var height = me.getHeight();
        var wrap = me.up('cfPanelTypeI');
        //		wrap.setHeight(wrap.getHeight() +110*arg);
        wrap.setHeight(height + 50);
    },
    variAdj: function (me) {
        var height = me.getHeight();
        var wrap = me.up('cfPanelTypeI');
        wrap.setHeight(height + 40);
    },
    deleteAppService: function (me, act, id, e) {
        if (act == 'deleteService') {
            Ext.Ajax.request({
                url: 'rest/service/deleteinstance',
                method: 'POST',
                params: {
                    serviceName: id
                },
                success: function (response) {
                    me.getStore().load({
                        params: {
                            first: 3
                        }
                    });
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                    }
                }
            });
        }

    },
    serviceLoad: function (me) {
        var store = me.store;
        var name = me.up('appListDetailsView').appName;
        store.load({
            params: {
                appName: name
            }
        });
    },
    showSerBindWin: function (view) {
        var serW = Ext.create('cfWeb.view.appManage.NewBindServiceWindow', {
            itemId: 'newBindServiceWindow'
        });
        var detailWin = view.up('appListDetailsView');
        serW.appName = detailWin.appName;
        serW.detailWin = detailWin;
        serW.show();
    },
    heightAdj: function (view, arg) {
        var window = view.up('cfWindow');
        var form = view.up('form');
        if (window) {
            var wHeight = window.getHeight();
            window.setHeight(wHeight + arg * 31);
        }
        if (form) {
            var fHeight = form.getHeight();
            form.setHeight(fHeight + arg * 31);
        }

    },
    bindService: function (me) {
        isOperayion = 1;
        var self = this;
        var win = me;
        var itemColor = win.detailWin.down('appHeadView').getValues().itemColor;
        var form = me.down('form');
        form.down('hiddenfield[name=appName]').setValue(me.appName);
        var serviceName = win.down('combobox[itemId=serCombo]').getValue();
        if (serviceName == '' || serviceName == undefined) {
            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.ChooseBindService);
            return;
        }
        var asd = win.detailWin.down('serviceDetail');
        console.log(asd);
        asd.data = [];
        if (serviceName == 'Oracle' || serviceName == 'MySQL') {
            var oracleConfig = me.down('configOracle');
            if (oracleConfig) {
                var res = oracleConfig.validate();
                if (!res) {
                    return false;
                }

                if (!oracleConfig.validateServiceRepeat()) {
                    return false;
                }
                if (!oracleConfig.validateSourceNameRepeat()) {
                    return false;
                }
            }
            console.log(oracleConfig.getValues());
            var data = oracleConfig.getValues();
            if (form.down('hiddenfield[name=serName]') != null) {
                form.remove(form.down('hiddenfield[name=serName]'), true);
            }

            if (form.down('hiddenfield[name=isMapping]') != null) {
                form.remove(form.down('hiddenfield[name=isMapping]'), true);
            }

            if (form.down('hiddenfield[name=isAuto]') != null) {
                form.remove(form.down('hiddenfield[name=isAuto]'), true);
            }
            if (data.isMapping == false) {

                for (var j = 0; j < data.service.length; j++) {
                    if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                        var res = oracleConfig.validateCombo();
                        if (!res) {
                            return false;
                        }
                    }
                }
            }
            if (data.isMapping == true) {
                for (var j = 0; j < data.service.length; j++) {
                    if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                        var res = oracleConfig.validateCombo();
                        if (!res) {
                            return false;
                        }
                    }
                }
                for (var i = 0; i < data.appSource.length; i++) {
                    console.log(data.appSource[i]);
                    if (data.appSource[i] == cfWebLang.AppManageView.InputDataSourceName || data.appSource[i] == '') {
                        var res = oracleConfig.validateText();
                        if (!res) {
                            return false;
                        }
                    } else {
                        var storeEnv = win.detailWin.down('variableListView').getStore();
                        for (var j = 0; j < storeEnv.data.length; j++) {
                            if (data.appSource[i] == storeEnv.data.items[j].data.key) {
                                var result = oracleConfig.validateEnvNameRepeat();
                                if (!result) {
                                    return false;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            var service = Ext.widget('hiddenfield', {
                name: 'serName',
                value: data.serName
            });
            form.add(service);
            var isMapping = Ext.widget('hiddenfield', {
                name: data.serName + 'Mapping',
                value: data.isMapping
            });
            form.add(isMapping);
            var isAuto = Ext.widget('hiddenfield', {
                name: 'isAuto',
                value: data.isAuto
            });
            form.add(isAuto);
            var lth = data.service.length;
            if (lth == 0) {
                waitWindow.close();
                return;
            }
            for (var i = 0; i < lth; i++) {
                var temp = Ext.widget('hiddenfield', {
                    name: 'appSource',
                    value: data.appSource[i]
                });
                form.add(temp);
                var temp2 = Ext.widget('hiddenfield', {
                    name: 'service',
                    value: data.service[i]
                });
                form.add(temp2);
            }
            var waitWindow = Ext.MessageBox.show({
                title: cfWebLang.CfWindow.inBindService,
                closable: false,
                cls: 'style-cfLoading'
            });
            console.log(form);
            form.submit({
                url: 'rest/app/bindOracleService',
                success: function (e, resp) {
                    win.close();
                    waitWindow.close();
                    var serviceDetail = win.detailWin.down('serviceDetail');
                    var serStore = serviceDetail.getStore();
                    var appName = me.appName;
                    serStore.load({
                        params: {
                            appName: appName
                        },
                        callback: function () {
                            serviceDetail.loadInit();
                            console.log(serStore.data.items);
                            var lth = serStore.data.items.length;

                            var serList = [];
                            for (var i = 0; i < lth; i++) {
                                serList.push(serStore.data.items[i].data.serviceName);
                            }
                            var head = me.detailWin.down('appHeadView');
                            head.updateAppStatus({
                                serviceName: serList
                            });
                            envReload();
                        }

                    });
                    var envReload = function () {
                        var variableListView = win.detailWin.down('variableListView');
                        console.log(variableListView);
                        var envStore = variableListView.getStore();
                        console.log(envStore);
                        envStore.load({
                            params: {
                                appName: appName
                            }
                        });
                    };
                    Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.afterBindSuccess);

                },
                failure: function (e, resp) {
                    waitWindow.close();
                    for (var i = 0; i < data.service.length; i++) {
                        form.remove(form.down('hiddenfield[value=' + data.service[i] + ']'), true);
                    }
                    for (var i = 0; i < data.appSource.length; i++) {
                        form.remove(form.down('hiddenfield[value=' + data.appSource[i] + ']'), true);
                    }
                    form.remove(form.down('hiddenfield[name=isMapping]'), true);
                    form.remove(form.down('hiddenfield[name=isAuto]'), true);
                    if (resp.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (resp.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var response = Ext.JSON.decode(resp.response.responseText);
                    if (!response.success && response.data != null) {
                        if (response.data.source == 1) {
                            Ext.MessageBox.show({
                                title: cfWebLang.ErrorSource.cloudfoundry,
                                msg: response.data.message,
                                cls: 'style-cfMessText',
                                buttons: Ext.MessageBox.OK
                            });
                            return;
                        } else if (response.data.source == 2) {
                            Ext.MessageBox.show({
                                title: cfWebLang.Util.Tip,
                                msg: cfWebLang.Util.failed,
                                cls: 'style-cfMessText',
                                buttons: Ext.MessageBox.OK
                            });
                            return;
                        }
                        var service = '';
                        var lth = response.data.length;
                        for (var i = 0; i < lth - 1; i++) {
                            service = service + response.data[i] + ',';
                        }
                        service = service + response.data[lth - 1];
                        Ext.MessageBox.show({
                            title: cfWebLang.Util.Tip,
                            msg: service + cfWebLang.CfWindow.ServiceAlreadyBinded,
                            cls: 'style-cfMessText',
                            buttons: Ext.MessageBox.OK
                        });
                    }
                }
            });
            return;
        }
        if (serviceName == 'logService') {
            var anaLog = win.down('logService[itemId=appAnaLog]');
            console.log(anaLog);
            var group = anaLog.down('checkboxgroup');
            console.log(group);
            for (var i = 0; i < group.items.length; i++) {
                console.log(group.items.items[i].boxLabel);
                asd.data.push(group.items.items[i].boxLabel);
            }
            var myMask = new Ext.LoadMask(me, {
                msg: cfWebLang.AppManageView.bounding
            });
            myMask.show();
            Ext.Ajax.request({
                url: 'rest/app/bindService',
                method: 'GET',
                params: {
                    appName: me.appName,
                    serviceName: serviceName.toLowerCase(),
                    data: asd.data
                },
                success: function (response) {
                    myMask.hide();
                    var obj = Ext.JSON.decode(response.responseText);
                    if (!obj.success) {
                        if (obj.source == 'patternExist') {
                            Ext.MessageBox.alert(cfWebLang.Util.Tip, 'pattern ' + obj.error + cfWebLang.CfWindow.patternExist);
                        }
                        return;
                    }
                    asd.store.load({
                        params: {
                            appName: me.appName
                        }
                    });
                    asd.loadInit();
                    asd.index = 0;
                    var headView = win.detailWin.down('appHeadView');
                    headView.serviceAdd(serviceName);
                    Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.afterBindSuccess);
                    win.close();
                },
                failure: function (response) {
                    myMask.hide();
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var obj = Ext.JSON.decode(response.responseText);
                    if (obj.data != null && obj.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                    }
                }
            });
            return;
        }
        var serviceInstanceName = win.down('#default_service_comb').getValue();
        var myMask = new Ext.LoadMask(me, {
            msg: cfWebLang.AppManageView.bounding
        });
        myMask.show();
        Ext.Ajax.request({
            url: 'rest/app/bindService',
            method: 'GET',
            params: {
                appName: me.appName,
                serviceName: serviceInstanceName
            },
            success: function (response) {
                myMask.hide();
                asd.store.load({
                    params: {
                        appName: me.appName
                    }
                });
                asd.loadInit();
                asd.index = 0;
                var headView = win.detailWin.down('appHeadView');
                headView.serviceAdd(serviceInstanceName);
                Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.afterBindSuccess);
                win.close();
            },
            failure: function (response) {
                myMask.hide();
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var obj = Ext.JSON.decode(response.responseText);
                if (obj.data != null && obj.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                }
            }
        });
    },
    renderApps: function (tab) {
        tab.getStore().load();
    },

    adaptHeight: function (group) {
        var win = group.up('newAppCfWindow');
        if (win != undefined)
            win.indexInit();
    },
    cfChartTypeIRenderAccess: function (tab) {
        var win = tab.up('appListDetailsView');
        var now = new Date(),
            year = now.getFullYear(),
            month = now.getMonth() + 1,
            day = now.getDate();
        var store = tab.getStore();
        store.setParams({
            appName: win.appName,
            from: year + '-' + month + '-' + day + ' 00:00:00',
            to: year + '-' + month + '-' + day + ' 23:59:59',
            step: '1h'
        }).load({
            callback: function (rec, opt, succ) {
                /*if(rec.length == 0) {
                 rec.push({name:' ',data:-1});
                 this.loadData(rec);
                 }*/
            }
        });
        accesstimer = setInterval(function () {
            store.load();
        }, 6000);
    },
    cfChartTypeIRenderHist: function (tab) {
        var win = tab.up('appListDetailsView');
        var now = new Date(),
            year = now.getFullYear(),
            month = now.getMonth() + 1,
            day = now.getDate();
        var store = tab.getStore();
        store.setParams({
            appName: win.appName,
            from: year + '-' + month + '-' + day + ' 00:00:00',
            to: year + '-' + month + '-' + day + ' 23:59:59',
            step: '1h'
        }).load({
            callback: function (rec, opt, succ) {
                if (rec.length == 0) {
                    rec.push({
                        name: ' ',
                        data: -1
                    });
                    this.loadData(rec);
                }
            }
        });
        latencytimer = setInterval(function () {
            store.load();
        }, 6000);

    },

    getAppInfoForTime: function (me, act, dom, e) {
        var win = me.up('appListDetailsView');
        var storeAccess = me.up('cfPanelTypeI').down('cfChartTypeI[itemId=access]').getStore(),
            storeHist = me.up('cfPanelTypeI').down('cfChartTypeI[itemId=hist]').getStore();
        var appName = win.appName;
        switch (act) {
            case 'today' :
            {
                var now = new Date(),
                    year = now.getFullYear(),
                    month = now.getMonth() + 1,
                    day = now.getDate();
                storeHist.setParams({
                    appName: appName,
                    from: year + '-' + month + '-' + day + ' 00:00:00',
                    to: year + '-' + month + '-' + day + ' 23:59:59',
                    step: '1h'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            });
                            storeHist.loadData(rec);
                        }
                    }
                });
                storeAccess.setParams({
                    appName: appName,
                    from: year + '-' + month + '-' + day + ' 00:00:00',
                    to: year + '-' + month + '-' + day + ' 23:59:59',
                    step: '1h'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            });
                            storeAccess.loadData(rec);
                        }
                    }
                });
                break;
            }
            case 'yesterday' :
            {
                var yesterday = new Date();
                yesterday.setDate(yesterday.getDate() - 1);
                var year = yesterday.getFullYear(),
                    month = yesterday.getMonth() + 1,
                    day = yesterday.getDate();
                storeHist.setParams({
                    appName: appName,
                    from: year + '-' + month + '-' + day + ' 00:00:00',
                    to: year + '-' + month + '-' + day + ' 23:59:59',
                    step: '1h'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            });
                            storeHist.loadData(rec);
                        }
                    }
                });
                storeAccess.setParams({
                    appName: appName,
                    from: year + '-' + month + '-' + day + ' 00:00:00',
                    to: year + '-' + month + '-' + day + ' 23:59:59',
                    step: '1h'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            });
                            storeAccess.loadData(rec);
                        }
                    }
                });
                break;
            }
            case 'thisWeek' :
            {
                var time = new Date();
                var fyear, fmonth, fday, tyear, tmonth, tday;
                if (time.getDay() != 0) {
                    time.setDate(time.getDate() - time.getDay() + 1);
                    fyear = time.getFullYear(),
                        fmonth = time.getMonth() + 1,
                        fday = time.getDate();
                    time.setDate(time.getDate() + 6);
                    tyear = time.getFullYear(),
                        tmonth = time.getMonth() + 1,
                        tday = time.getDate();
                } else {
                    tyear = time.getFullYear(),
                        tmonth = time.getMonth() + 1,
                        tday = time.getDate();
                    time.setDate(time.getDate() - 6);
                    fyear = time.getFullYear(),
                        fmonth = time.getMonth() + 1,
                        fday = time.getDate();
                }
                storeHist.setParams({
                    appName: appName,
                    from: fyear + '-' + fmonth + '-' + fday + ' 00:00:00',
                    to: tyear + '-' + tmonth + '-' + tday + ' 23:59:59',
                    step: '1d'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            }); //'起始时间必须小于或等于结束时间！'
                            storeHist.loadData(rec);
                        }
                    }
                });
                storeAccess.setParams({
                    appName: appName,
                    from: fyear + '-' + fmonth + '-' + fday + ' 00:00:00',
                    to: tyear + '-' + tmonth + '-' + tday + ' 23:59:59',
                    step: '1d'
                }).load({
                    callback: function (rec, opt, succ) {
                        if (rec.length == 0) {
                            rec.push({
                                name: ' ',
                                data: -1
                            });
                            storeAccess.loadData(rec);
                        }
                    }
                });
                break;
            }
            case 'calendar' :
            {
                var process = function (me, date, eOpts) {
                    var time = new Date(date);
                    dom.setAttribute('data-time', time.getTime());
                    var y = time.getFullYear();
                    var m = time.getMonth() + 1;
                    var d = time.getDate();
                    dom.setAttribute('title', y + '/' + m + '/' + d);
                    var year = time.getFullYear();
                    var month = time.getMonth() + 1;
                    var day = time.getDate();
                    console.log('year:' + year);
                    console.log('month:' + month);
                    console.log('day:' + day);
                    storeHist.setParams({
                        appName: appName,
                        from: year + '-' + month + '-' + day + ' 00:00:00',
                        to: year + '-' + month + '-' + day + ' 23:59:59',
                        step: '1h'
                    }).load({
                        callback: function (rec, opt, succ) {
                            if (rec.length == 0) {
                                rec.push({
                                    name: ' ',
                                    data: -1
                                });
                                storeHist.loadData(rec);
                            }
                        }
                    });
                    storeAccess.setParams({
                        appName: appName,
                        from: year + '-' + month + '-' + day + ' 00:00:00',
                        to: year + '-' + month + '-' + day + ' 23:59:59',
                        step: '1h'
                    }).load({
                        callback: function (rec, opt, succ) {
                            if (rec.length == 0) {
                                rec.push({
                                    name: ' ',
                                    data: -1
                                });
                                storeAccess.loadData(rec);
                            }
                        }
                    });
                    me.destroy();
                };
                var time = dom.getAttribute('data-time');
                if (!time) {
                    time = new Date().getTime();
                }
                var datePicker = Ext.widget('datepicker', {
                    floating: true,
                    modal: true,
                    defaultDate: time,
                    listeners: {
                        'select': process
                    }
                });
                datePicker.showAt(e.getXY());

                break;
            }
        }
    },
    patternTest: function (btn) {
        window.open('http://grokdebug.herokuapp.com/');
    },

    onNewAppLoadTemRender: function (view) {
        var store = view.down('combobox[itemId=domain]').getStore();
        store.load();
        //		store=view.down('combobox[name=template.org]').getStore();
        //		store.load();
        //		store=view.down('combobox[name=template.space]').getStore();
        //		store.load();
    },
    onAppTemplateRender: function (view) {
        var store = view.down('combobox[itemId=templateOrg]').getStore();
        store.load();

        var storeDomain = view.down('combobox[itemId=templateDomain]').getStore();
        store.load();

    },
    add: function (me) {
        //
    },
    itemAdd: function (me) {
        var win = Ext.widget('appTemplateView', {
            isEdit: false
        });
        win.show();
    },
    appNewNext: function () {
        this.appAddWindowS.hide();
        this.appAddWindowE = this.getView('appManage.AppNewEndWindow').create();
        this.appAddWindowE.show();
    },
    appNewComplete: function () {
        this.appAddWindowE.close();
        alert('you have push a app');
    },
    menuClick: function (me, act, id, e) {
        //		alert(act);
        console.log(act.itemName);
        itemName = act.itemName;
        console.log('id:' + id);
        console.log(e);
        console.log(act.itemId);
        //var store = Ext.getCmp('temp').getStore();
        //console.log(store);
        //store.clearFilter();
        var self = this;
        if (id == 'new') {
            Ext.Ajax.request({
                url: 'rest/template/getone?id=' + act.itemId,
                async: false,
                success: function (res) {
                    var data = Ext.decode(res.responseText).data;
                    console.log(data);
                    var space = data.space;
                    Ext.Ajax.request({
                        url: 'rest/user/isAdmin',
                        method: 'GET',
                        aysnc: false,
                        success: function (resp) {
                            var isUserAdmin = Ext.JSON.decode(resp.responseText).isAdmin;
                            var isAuth = false;
                            if (isUserAdmin == false) {
                                Ext.Ajax.request({
                                    url: 'rest/user/currentuserRole',
                                    method: 'GET',
                                    async: false,
                                    success: function (resp) {
                                        var data = Ext.decode(resp.responseText).data;
                                        var length = data.length;
                                        for (var j = 0; j < length; j++) {
                                            if (data[j].authType == 'SpaceDeveloper' && data[j].spaceName == space) {
                                                console.log(isAuth);
                                                isAuth = true;
                                                break;
                                            }
                                        }
                                        if (isAuth == false) {
                                            Ext.MessageBox.show({
                                                title: cfWebLang.Util.Tip,
                                                msg: cfWebLang.Util.UploadAuth,
                                                cls: 'style-cfMessText',
                                                buttons: Ext.MessageBox.OK
                                            });
                                        }
                                    }
                                });
                            }
                            if (isUserAdmin == true || isAuth == true) {
                                var window = Ext.widget('newAppCfWindow', {
                                    langSet: {
                                        'next': cfWebLang.Util.Next,
                                        'prev': cfWebLang.Util.Prev,
                                        'finish': cfWebLang.Util.Finish
                                    }
                                });
                                var LoadTemView = Ext.widget('newAppLoadTem');
                                window.add(LoadTemView);
                                this.stoListserName = '';
                                this.anaListserNameDis = '';
                                this.appListserNameDis = '';

                                this.NewAppWindow = window;
                                this.anaListserNameLength = data.anaList.length;
                                this.stoListserNameLength = data.stoList.length;
                                this.appListserNameLength = data.appList.length;
                                this.appListserName = null;
                                this.stoListserName = null;
                                this.appListserNameDis = '';
                                this.anaListserName = null;
                                this.anaListserNameDis = '';
                                i = 0;
                                if (data.env) {
                                    this.envName = data.env.envName;
                                } else {
                                    this.envName = '';
                                }
                                if (this.stoListserNameLength != 0) {
                                    this.stoListserName = data.stoList[i].serName;
                                    for (var i = 0; i < this.stoListserNameLength; i++) {
                                        var stoListView = Ext.widget('serviceConfigView', {
                                            serType: cfWebLang.HomeTabView.dataStorageService,
                                            serName: data.stoList[i].serName
                                        });
                                        if (data.stoList[i].serName == 'Oracle' || data.stoList[i].serName == 'MySQL') {
                                            var view = Ext.widget(data.stoList[i].serName, {
                                                title: data.stoList[i].serName,
                                                store: Ext.create('cfWeb.store.dataStorage.DatabaseServiceSelectStore')
                                            });
                                            stoListView.add(view);
                                            console.log(view.store);
                                            view.store.load({
                                                params: {
                                                    first: 1,
                                                    second: data.stoList[i].id
                                                }
                                            });
                                        } else {
                                            var view = Ext.widget('view');
                                            stoListView.add(view);
                                        }
                                        window.add(stoListView);
                                    }
                                }

                                if (this.anaListserNameLength != 0) {
                                    i = 0;
                                    var langChange = undefined;
                                    if (data.anaList[i].serName == 'report' || data.anaList[i].serName == '报表') {
                                        langChange = cfWebLang.Service.report;
                                    }
                                    if (data.anaList[i].serName == 'batchData' || data.anaList[i].serName == '批量数据') {
                                        langChange = cfWebLang.Service.batchData;
                                    }
                                    if (data.anaList[i].serName == 'flowData' || data.anaList[i].serName == '流数据') {
                                        langChange = cfWebLang.Service.flowData;
                                    }
                                    this.anaListserName = data.anaList[i].serName;
                                    this.anaListserNameDis = langChange;
                                    for (i = 0; i < this.anaListserNameLength; i++) {
                                        var anaListView = Ext.widget('serviceConfigView', {
                                            serType: cfWebLang.HomeTabView.dataAnalyseService,
                                            serName: data.anaList[i].serName
                                        });
                                        var view = Ext.widget('view');
                                        anaListView.add(view);
                                        window.add(anaListView);
                                    }
                                }

                                if (this.appListserNameLength != 0) {
                                    i = 0;
                                    this.appListserName = data.appList[i].serName;
                                    var langChange = undefined;
                                    if (data.appList[i].serName == '日志服务' || data.appList[i].serName == 'logService') {
                                        langChange = cfWebLang.Service.logService;
                                    } else if (data.appList[i].serName == 'pushService' || data.appList[i].serName == '推送服务') {
                                        langChange = cfWebLang.Service.pushService;
                                    } else if (data.appList[i].serName == '单点登陆' || data.appList[i].serName == 'SSO') {
                                        langChange = cfWebLang.Service.SSO;
                                    } else if (data.appList[i].serName == '中央认证服务' || data.appList[i].serName == 'CAS') {
                                        langChange = cfWebLang.Service.CAS;
                                    } else if (data.appList[i].serName == 'Email' || data.appList[i].serName == '电子邮件') {
                                        langChange = cfWebLang.Service.Email;
                                    } else if (data.appList[i].serName == 'dataExchange' || data.appList[i].serName == '数据交换') {
                                        langChange = cfWebLang.Service.dataExchange;
                                    } else if (data.appList[i].serName == '应用查询服务' || data.appList[i].serName == 'appServiceQuery') {
                                        langChange = cfWebLang.Service.appServiceQuery;
                                    } else {
                                        langChange = data.appList[i].serName;
                                    }
                                    this.appListserNameDis = langChange;
                                    for (i = 0; i < this.appListserNameLength; i++) {
                                        var appListView = Ext.widget('serviceConfigView', {
                                            serType: cfWebLang.HomeTabView.appService,
                                            serName: data.appList[i].serName
                                        });
                                        if (data.appList[i].serName == 'logService') {
                                            var view = Ext.widget(data.appList[i].serName);
                                            console.log(data.appList[i]);
                                            appListView.add(view);
                                        } else {
                                            var view = Ext.widget('view');
                                            appListView.add(view);
                                        }
                                        window.add(appListView);
                                    }
                                }
                                if (this.anaListserNameLength != 0) {
                                    for (i = 1; i < this.anaListserNameLength; i++) {
                                        var langChange = undefined;
                                        if (data.anaList[i].serName == 'report' || data.anaList[i].serName == '报表') {
                                            langChange = cfWebLang.Service.report;
                                        }
                                        if (data.anaList[i].serName == 'batchData' || data.anaList[i].serName == '批量数据') {
                                            langChange = cfWebLang.Service.batchData;
                                        }
                                        if (data.anaList[i].serName == 'flowData' || data.anaList[i].serName == '流数据') {
                                            langChange = cfWebLang.Service.flowData;
                                        }
                                        this.anaListserName = this.anaListserName + ' ' + data.anaList[i].serName;
                                        this.anaListserNameDis = this.anaListserNameDis + ' ' + langChange;
                                    }
                                    ;
                                }
                                if (this.stoListserNameLength != 0) {
                                    for (i = 1; i < this.stoListserNameLength; i++) {
                                        this.stoListserName = this.stoListserName + ' ' + data.stoList[i].serName;
                                    }
                                }
                                if (this.appListserNameLength != 0) {
                                    for (i = 1; i < this.appListserNameLength; i++) {
                                        var langChange = undefined;
                                        if (data.appList[i].serName == '日志服务' || data.appList[i].serName == 'logService') {
                                            langChange = cfWebLang.Service.logService;
                                        } else if (data.appList[i].serName == 'pushService' || data.appList[i].serName == '推送服务') {
                                            langChange = cfWebLang.Service.pushService;
                                        } else if (data.appList[i].serName == '单点登陆' || data.appList[i].serName == 'SSO') {
                                            langChange = cfWebLang.Service.SSO;
                                        } else if (data.appList[i].serName == '中央认证服务' || data.appList[i].serName == 'CAS') {
                                            langChange = cfWebLang.Service.CAS;
                                        } else if (data.appList[i].serName == 'Email' || data.appList[i].serName == '电子邮件') {
                                            langChange = cfWebLang.Service.Email;
                                        } else if (data.appList[i].serName == 'dataExchange' || data.appList[i].serName == '数据交换') {
                                            langChange = cfWebLang.Service.dataExchange;
                                        } else if (data.appList[i].serName == '应用查询服务' || data.appList[i].serName == 'appServiceQuery') {
                                            langChange = cfWebLang.Service.appServiceQuery;
                                        } else {
                                            langChange = data.appList[i].serName;
                                        }
                                        this.appListserName = this.appListserName + ' ' + data.appList[i].serName;
                                        this.appListserNameDis = this.appListserNameDis + ' ' + langChange;
                                    }
                                }
                                console.log(data);
                                Ext.define('model', {
                                    extend: 'Ext.data.Model',
                                    fields: ['template.temName', 'env.envName',
                                        'template.id',
                                        'stoList.serName', 'anaList.serName',
                                        'appList.serName', 'template.domain',
                                        'template.instance', 'template.envId',
                                        'org', 'space', 'template.memory'
                                    ]
                                });
                                var rec = Ext.create('model', {
                                    'template.domain': data.template.domain,
                                    'template.id': data.template.id,
                                    'template.temName': data.template.temName,
                                    'env.envName': this.envName,
                                    'stoList.serName': this.stoListserName,
                                    'anaList.serName': this.anaListserName,
                                    'appList.serName': this.appListserName,
                                    'template.instance': data.template.instance,
                                    'template.envId': data.template.envId,
                                    'org': data.org,
                                    'space': data.space,
                                    'template.memory': data.template.memory
                                });
                                var form = window.down('form[name=LoadTem.Form]');
                                form.loadRecord(rec);
                                window.down('displayfield[itemId=temName]').setValue(data.template.temName);
                                window.down('displayfield[itemId=envName]').setValue(this.envName);
                                window.down('displayfield[itemId=stoSerName]').setValue(this.stoListserName);
                                window.down('displayfield[itemId=anaSerName]').setValue(this.anaListserNameDis);
                                window.down('displayfield[itemId=appSerName]').setValue(this.appListserNameDis);
                                window.down('displayfield[itemId=org]').setValue(data.org);
                                window.down('displayfield[itemId=space]').setValue(data.space);
                                window.down('combobox[itemId=memory]').setValue(data.template.memory);

                                window.show();
                            }
                        },
                        failure: function (response) {
                            if (response.status == '401') {
                                Ext.Msg.show({
                                    title: cfWebLang.Util.Tip,
                                    id: 'firstWin',
                                    msg: cfWebLang.Main.SessionOverdue,
                                    width: 250,
                                    buttons: Ext.MessageBox.OK,
                                    fn: function () {
                                        parent.location.href = '/cfWeb/login.html';
                                    },
                                    cls: 'overtimeWin'
                                });
                                //Ext.WindowManager.bringToFront ('firstWin');
                                /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                                 parent.location.href = '/cfWeb/login.html';
                                 }); */
                                return;
                            }

                            if (response.timedout) {
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                                return;
                            }
                            var obj = Ext.JSON.decode(response.responseText);
                            if (obj.data != null && obj.data.source == 1) {
                                Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                            } else {
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                            }
                        }
                    });
                }
            });
        }

        if (id == 'detail') {
            var win = Ext.widget('appTemplateDetailView');
            win.show();
            Ext.Ajax.request({
                url: 'rest/template/getone?id=' + act.itemId,
                success: function (res) {
                    var data = Ext.decode(res.responseText).data;
                    var domain = data.template.domain;
                    var memory = data.template.memory;
                    var instance = data.template.instance;
                    var temName = data.template.temName;
                    var evnName = data.env.envName;

                    var stoListStr = data.stoList.map(function (o) {
                        return o.serName;
                    }).join(',');

                    var anaListStr = data.anaList.map(function (o) {
                        return cfWebLang.Service[o.serName] || o.serName;
                    }).join(',');
                    var appListStr = data.appList.map(function (o) {
                        return cfWebLang.Service[o.serName] || o.serName;
                    }).join(',');
                    if (memory < 1024) {
                        memory += 'M';
                    } else {
                        memory = memory / 1024 + 'G';
                    }
                    Ext.getCmp('appTextfield').setValue(evnName);
                    Ext.getCmp('storageTextfield').setValue(stoListStr || '空');
                    Ext.getCmp('analyseTextfield').setValue(anaListStr || '空');
                    Ext.getCmp('serviceTextfield').setValue(appListStr || '空');
                    Ext.getCmp('domainTextfield').setValue(domain);
                    Ext.getCmp('memoryTextfield').setValue(memory);
                    Ext.getCmp('instanceTextfield').setValue(instance);
                    Ext.getCmp('temNameTextfield').setValue(temName);
                }
            })
        }
        if (id == 'edit') {
            var win = Ext.widget('appTemplateView', {
                isEdit: true,
                id: act.itemId
            });
            var view = win.down('moduleConstructView');
            var store = view.getStore();
            win.show();
            Ext.Ajax.request({
                url: 'rest/template/getone?id=' + act.itemId,
                success: function (res) {
                    var data = Ext.decode(res.responseText).data;
                    var org = data.org;
                    var space = data.space;
                    var domain = data.template.domain;
                    var memory = data.template.memory;
                    var instance = data.template.instance;
                    var temName = data.template.temName;


                    var stoLen = data.stoList.length;
                    var anaLen = data.anaList.length;
                    var appLen = data.appList.length;

                    var evnName = data.env.envName;
                    var envId = data.env.id;
                    var envImg = data.env.envImg;
                    var insert = {};
                    insert.buildPack = {
                        name: evnName,
                        id: envId,
                        img: envImg
                    };
                    view.addItem(insert);
                    for (var i = 0; i < stoLen; i++) {
                        insert = {};
                        insert.serType1 = {
                            name: cfWebLang.Service[data.stoList[i].serName],
                            id: data.stoList[i].id,
                            img: data.stoList[i].serImg
                        };
                        view.addItem(insert);
                    }
                    for (var i = 0; i < anaLen; i++) {
                        insert = {};
                        insert.serType2 = {
                            name: cfWebLang.Service[data.anaList[i].serName],
                            id: data.anaList[i].id,
                            img: data.anaList[i].serImg
                        };
                        view.addItem(insert);
                    }
                    for (var i = 0; i < appLen; i++) {
                        insert = {};
                        insert.serType3 = {
                            name: cfWebLang.Service[data.appList[i].serName],
                            id: data.appList[i].id,
                            img: data.appList[i].serImg
                        };
                        view.addItem(insert);
                    }

                    Ext.getCmp('templateDomain').setValue(domain);
                    Ext.getCmp('memory').setValue(memory);
                    Ext.getCmp('instance').setValue(instance);
                    Ext.getCmp('temName').setValue(temName);

                }
            });
        }
        if (id == 'delete') {
            var store = me.getStore();
            var callback = function (btn) {
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: 'rest/template/delete?id=' + act.itemId,
                        method: 'DELETE',
                        success: function (resp) {
                            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.DeleteSuccess);
                            store.load();
                            me.close();
                        },
                        failure: function (response) {
                            if (response.status == '401') {
                                Ext.Msg.show({
                                    title: cfWebLang.Util.Tip,
                                    id: 'firstWin',
                                    msg: cfWebLang.Main.SessionOverdue,
                                    width: 250,
                                    buttons: Ext.MessageBox.OK,
                                    fn: function () {
                                        parent.location.href = '/cfWeb/login.html';
                                    },
                                    cls: 'overtimeWin'
                                });
                                //Ext.WindowManager.bringToFront ('firstWin');
                                /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                                 parent.location.href = '/cfWeb/login.html';
                                 }); */
                                return;
                            }

                            if (response.timedout) {
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                                return;
                            }
                            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.DeleteFailed);
                        }
                    });
                }
            };
            Ext.Msg.confirm(cfWebLang.Util.ConfirmWindow, cfWebLang.Util.DeleteConfirm, callback);
        }
    },
    cbuttonMenuClick: function (me, act, name, pos, e) {
        var self = this;
        if (act == 'update') {
            var win = Ext.widget('appUploadWindow');
            win.appName = name;
            win.action = me;
            win.pos = pos;
            me.actionDone(pos);
            var itemData = me.getStore().getAt(pos.pindex);
            if (itemData.data.appList[pos.index].relatedApp) {
                win.down('checkbox#isGrayUpdate').hide();
            }
            win.show();
            return;
        }
        if (act == 'details') {
            me.actionDone(pos);
            var itemData = me.getStore().getAt(pos.pindex);
            console.log(itemData.data);
            var mainView = Ext.ComponentQuery.query('mainView')[0];
            var x = mainView.getX();
            var width = mainView.getWidth() - 10;
            var height = mainView.getHeight();
            var win = Ext.widget('appListDetailsView', {
                adaptTo: mainView,
                blankHeight: 50,
                //				blankHeight:height-100,
                width: width,
                height: height
            });
            win.appName = name;
            win.slideUp();
            self.window = win;
            var appData = {
                itemImg: '',
                title: '',
                message: '',
                itemColor: '',
                status: '',
                instance: '',
                memory: '',
                space: '',
                runtime: '',
                serviceName: '',
                instanceStatus: '',
                domain: ''
            };
            appData = itemData.data.appList[pos.index];
            appData.serviceName = appData.service;
            appData.domain = null;
            appData.instanceStatus = null;
            appData.space = itemData.raw.appList[pos.index].cloudApp.entity.disk_quota;

            win.items.items[0].updateAppStatus(appData);
            Ext.Ajax.request({
                url: 'rest/domain/listall',
                method: 'GET',
                async: false,
                success: function (response) {
                    var obj = Ext.JSON.decode(response.responseText);
                    var domainlist = [];
                    var data = obj.data;
                    for (var i = 0; i < data.length; i++) {
                        domainlist[i] = data[i].name;
                    }
                    win.items.items[0].domainList = domainlist;
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var obj = Ext.JSON.decode(response.responseText);
                    if (obj.data != null && obj.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                    }
                }
            });
            Ext.Ajax.request({
                url: 'rest/app/details',
                method: 'GET',
                params: {
                    appName: name
                },
                success: function (response) {
                    var obj = Ext.JSON.decode(response.responseText);
                    var service = [];
                    if (obj.serviceName != null)
                        win.items.items[0].updateAppStatus(obj);
                    //调节参数设置
                    win.down('#instanceSlider').setValue(obj.instance);
                    //					var Gmemory=obj.memory/1024.0;
                    win.down('#memorySlider').setValue(obj.memory);
                    win.down('thresholdControlView').setMode(obj.autoScale);
                    if (obj.max_cpu != null && obj.min_cpu != null) {
                        win.down('#cpuMultiSlider').setValue([obj.min_cpu, obj.max_cpu], true);
                    } else {
                        win.down('#cpuMultiSlider').setValue([0, 0], true);
                    }

                    if (obj.max_instance != null && obj.min_instance != null) {
                        win.down('#instanceMultiSlider').setValue([obj.min_instance, obj.max_instance], true);
                    } else {
                        win.down('#instanceMultiSlider').setValue([1, 1], true);
                    }
                    win.down('cfPanelTypeI[itemId=appIns]').down('switchContentView').setValue(obj.instStatus);
                    self.updateChartData(win.down('cfPanelTypeI[itemId=appIns]').down('switchContentView'));
                    console.log(obj);

                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var obj = Ext.JSON.decode(response.responseText);
                    if (obj.data != null && obj.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                    }
                }
            });
            //			window.show();
        } else if (act == 'unbindService') {
            isOperayion = 1;
            var win = me.up('appListDetailsView');
            var appName = win.appName;
            Ext.Msg.confirm(cfWebLang.Util.ConfirmWindow, cfWebLang.Util.Unbunding, function (btn) {
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: 'rest/app/unbindService',
                        method: 'GET',
                        params: {
                            appName: appName,
                            serviceName: me.store.getAt(pos.pindex).appList[pos.index].get('serviceName')
                        },
                        success: function (response) {
                            console.log(me.store.getCount());
                            me.store.removeAt(index);
                            me.store.loadData(me.store.data.items);
                            me.loadInit();
                            console.log(me.store.getCount());
                            var temp = [];
                            for (var i = 0; i < me.store.getCount(); i++) {
                                console.log(me.store.getAt(i).get('serviceName'));
                                temp[temp.length] = me.store.getAt(i).get('serviceName');
                            }
                            console.log(temp);
                            var data = {
                                serviceName: temp
                            };
                            me.ownerCt.ownerCt.previousSibling().updateAppStatus(data);
                            me.actionDone(index);
                            var envReload = function () {
                                var variableListView = win.down('variableListView');
                                console.log(variableListView);
                                var envStore = variableListView.getStore();
                                console.log(envStore);
                                envStore.load({
                                    params: {
                                        appName: appName
                                    }
                                });
                            };
                            envReload();
                            Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.afterunBindSuccess);
                        },
                        failure: function (response) {
                            if (response.status == '401') {
                                Ext.Msg.show({
                                    title: cfWebLang.Util.Tip,
                                    id: 'firstWin',
                                    msg: cfWebLang.Main.SessionOverdue,
                                    width: 250,
                                    buttons: Ext.MessageBox.OK,
                                    fn: function () {
                                        parent.location.href = '/cfWeb/login.html';
                                    },
                                    cls: 'overtimeWin'
                                });
                                //Ext.WindowManager.bringToFront ('firstWin');
                                /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                                 parent.location.href = '/cfWeb/login.html';
                                 }); */
                                return;
                            }

                            if (response.timedout) {
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                                return;
                            }
                            var obj = Ext.JSON.decode(response.responseText);
                            if (obj.data != null && obj.data.source == 1) {
                                Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                            } else {
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.failed);
                            }
                            me.actionDone(pos);
                        }
                    });

                } else {
                    me.actionDone(pos);
                }
            });
        } else {
            Ext.Ajax.request({
                url: 'rest/app/' + act + '?appName=' + name,
                method: 'GET',
                success: function (resp) {
                    /*if(self.STATUS[act] != null) {
                     me.getStore().getAt(index).set('status',self.STATUS[act]);
                     me.getStore().load();
                     }
                     if(act == 'delete') {
                     me.removeAt(index);
                     }*/
                    me.getStore().load();
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                    me.actionDone(pos);
                }
            });
        }

    },
    appClick: function (me, name, index, e) {
        this.cbuttonMenuClick(me, 'details', name, index, e);
        //
    },
    onsearch: function (keyword, me) {
        var title = me.title;
        if (title == '系统模板') {
            var store = me.down('lbuttonIconListView').store;
            store.clearFilter();
            store.filter('itemName', new RegExp('/*' + keyword, 'i'));
        } else if (title == '应用监控') {
            var store = me.down('cbuttonIconListView').store;
            store.clearFilter();
            store.filter('title', new RegExp('/*' + keyword, 'i'));
        }
    },
    search: function (me) {
        var title = me.title;

        if (title == '系统模板') {
            var store = me.down('lbuttonIconListView').store;
            store.clearFilter();
        } else if (title == '应用监控') {
            var store = me.down('cbuttonIconListView').store;
            store.clearFilter();
        }
    },
    formValidate: function (me, oldIndex, newIndex) {
        //		console.log("!!!!!!!!!!!!!!!");
        var oldForm = oldIndex.down('form');
        console.log(oldIndex);
        if (oldForm == null) {
            oldForm = {};
            oldForm.name = '';
        }
        //		var oldForm=oldIndex.down('form');
        //		var newForm=newIndex.down('form');
        //		新建应用添加其它页面的过程中，表单验证会产生影响，先注释掉之后一起验证
        console.log(oldForm);
        if (oldForm.name == 'LoadTem.Form') {
            var appName = oldForm.down('textfield[itemId=appName]');
            var appNameTip = oldForm.down('displayfield[itemId=errorTip]');
            var fileCheckbox = oldForm.down('checkbox[itemId=upFile]');
            var appCheckbox = oldForm.down('checkbox[itemId=upApp]');
            var uploadFile = oldForm.down('filefield');
            var uploadFileTip = oldForm.down('displayfield[itemId=fileTip]');
            var domainName = oldForm.down('combobox[itemId=domain]');
            if (appName.getValue() == '') {
                appNameTip.setValue(cfWebLang.CfWindow.UsernameEmpty);
                appNameTip.setVisible(true);
                //("validate1");
                return false;
            } else if (domainName.getValue() == '' || domainName.getValue() == null && appNameTip.isHidden() == true) {
                appNameTip.setValue(cfWebLang.CfWindow.domainNameEmp);
                appNameTip.setVisible(true);
                return false;
            } else if (fileCheckbox.checked && uploadFile.getValue() == '') {
                uploadFileTip.setVisible(true);
                return false;
            } else if (fileCheckbox.checked == false && appCheckbox.checked == false) {
                //("validate2");
                oldForm.down('displayfield[itemId=chooseTip]').setVisible(true);
                return false;
            } else {
                //("validate4");
            }
        }
        if (oldIndex.serName == 'Oracle' || oldIndex.serName == 'MySQL') {
            var serName = oldIndex.serName;
            var config = oldIndex.down(serName);
            config.down('label[itemId=tipAdd]').setVisible(false);
            config.down('label[itemId=tipCombo]').setVisible(false);
            config.down('label[itemId=tipServiceConflict]').setVisible(false);
            console.log(config);
            if (config) {
                var res = config.validate();
                if (!res) {
                    return false;
                }
            }
            var data = config.getValues();
            if (!config.validateServiceRepeat()) {
                return false;
            }
            if (data.isMapping == true) {
                for (var i = 0; i < data.appSource.length; i++) {
                    if (data.appSource[i] == cfWebLang.AppManageView.InputDataSourceName || data.appSource[i] == '') {
                        var res = config.validateText();
                        if (!res) {
                            return false;
                        }
                    }
                }
                for (var j = 0; j < data.service.length; j++) {
                    if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                        var res = config.validateCombo();
                        if (!res) {
                            return false;
                        }
                    }
                }
            }
            if (data.isMapping == false) {
                for (var j = 0; j < data.service.length; j++) {
                    if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                        var res = config.validateCombo();
                        if (!res) {
                            return false;
                        }
                    }
                }
            }

        }


        return true;
    },
    submitForm: function (me) {
        var window = me;
        var lth = window.items.items.length;
        console.log(window.items.items[1]);
        if (lth == 1) {
            var formLoad = window.items.items[0];
            var appName = formLoad.down('textfield[itemId=appName]');
            var appNameTip = formLoad.down('displayfield[itemId=errorTip]');
            var fileCheckbox = formLoad.down('checkbox[itemId=upFile]');
            var appCheckbox = formLoad.down('checkbox[itemId=upApp]');
            var uploadFile = formLoad.down('filefield');
            var uploadFileTip = formLoad.down('displayfield[itemId=fileTip]');
            var domainName = formLoad.down('combobox[itemId=domain]');
            if (appName.getValue() == '') {
                appNameTip.setValue(cfWebLang.CfWindow.UsernameEmpty);
                appNameTip.setVisible(true);
                //("validate1");
                return false;
            } else if (domainName.getValue() == '' || domainName.getValue() == null && appNameTip.isHidden() == true) {
                appNameTip.setValue(cfWebLang.CfWindow.domainNameEmp);
                appNameTip.setVisible(true);
                return false;
            } else if (fileCheckbox.checked && uploadFile.getValue() == '') {
                uploadFileTip.setVisible(true);
                return false;
            } else if (fileCheckbox.checked == false && appCheckbox.checked == false) {
                //("validate2");
                formLoad.down('displayfield[itemId=chooseTip]').setVisible(true);
                return false;
            } else {
                //("validate4");
            }
        }
        for (var i = 1; i < lth; i++) {
            var serName = window.items.items[i].serName;
            if (serName == 'Oracle' || serName == 'MySQL') {
                var config = window.items.items[i].down('configOracle');
                if (config) {
                    var res = config.validate();
                    if (!res) {
                        return false;
                    }

                    if (!config.validateServiceRepeat()) {
                        return false;
                    }
                }
                var data = window.items.items[i].down('configOracle').getValues();
                if (data.isMapping == true) {
                    for (var j = 0; j < data.appSource.length; j++) {
                        if (data.appSource[j] == cfWebLang.AppManageView.InputDataSourceName || data.appSource[j] == '') {
                            var res = config.validateText();
                            if (!res) {
                                return false;
                            }
                        }
                    }
                    for (var j = 0; j < data.service.length; j++) {
                        if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                            var res = config.validateCombo();
                            if (!res) {
                                return false;
                            }
                        }
                    }
                }
                if (data.isMapping == false) {
                    for (var j = 0; j < data.service.length; j++) {
                        if (data.service[j] == cfWebLang.AppManageView.ChooseSource || data.service[j] == '') {
                            var res = config.validateCombo();
                            if (!res) {
                                return false;
                            }
                        }
                    }
                }
                var tarForm = window.items.items[0].down('form');
                var service = Ext.widget('hiddenfield', {
                    name: 'serName',
                    value: data.serName
                });
                tarForm.add(service);
                var isMapping = Ext.widget('hiddenfield', {
                    name: data.serName + 'Mapping',
                    value: data.isMapping
                });
                tarForm.add(isMapping);
                var isAuto = Ext.widget('hiddenfield', {
                    name: 'isAuto',
                    value: data.isAuto
                });
                tarForm.add(isAuto);
                var slth = data.service.length;
                if (slth == 0) {
                    return;
                }
                for (var j = 0; j < slth; j++) {
                    var temp = Ext.widget('hiddenfield', {
                        name: 'appSource',
                        value: data.appSource[j]
                    });
                    tarForm.add(temp);
                    var temp2 = Ext.widget('hiddenfield', {
                        name: 'service',
                        value: data.service[j]
                    });
                    tarForm.add(temp2);
                }
            }
        }
        var form = new Ext.form.Basic(window, {});
        var appList = Ext.getCmp('temp');
        var appListStore = appList.getStore();
        var waitWindow = Ext.MessageBox.show({
            title: cfWebLang.Util.CreateApp,
            closable: false,
            cls: 'style-cfLoading'
        });
        form.submit({
            url: 'rest/app/upload',
            //			url:'/rest/app/test',
            success: function (e, resp) {
                window.close();
                waitWindow.close();
                appListStore.load();
            },
            failure: function (e, resp) {
                appListStore.load();
                window.close();
                waitWindow.close();
                if (resp.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (resp.timedout) {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        msg: cfWebLang.global.timeout,
                        cls: 'style-cfMessText',
                        buttons: Ext.MessageBox.OK
                    });
                    return;
                }
                var error = Ext.JSON.decode(resp.response.responseText);
                if (error.data != null && error.data.source == 1) {
                    Ext.MessageBox.show({
                        title: cfWebLang.ErrorSource.cloudfoundry,
                        msg: error.data.message,
                        cls: 'style-cfMessText',
                        buttons: Ext.MessageBox.OK
                    });
                } else if (error.source == 'patternExist') {
                    Ext.MessageBox.alert({
                        title: cfWebLang.Util.Tip,
                        msg: 'pattern ' + error.error + cfWebLang.CfWindow.patternExist,
                        cls: 'style-cfMessText',
                        buttons: Ext.MessageBox.OK
                    });
                } else {
                    Ext.MessageBox.alert({
                        title: cfWebLang.ErrorSource.app,
                        msg: cfWebLang.Error.SystemError,
                        cls: 'style-cfMessText',
                        buttons: Ext.MessageBox.OK
                    });
                }

            }
        });

    },
    submitTemplateView: function (me) {
        var win = me;
        var moduleView = Ext.ComponentQuery.query('collapsibleBlock lbuttonIconListView')[0];

        var store = moduleView.getStore();

        var temp = me.down('moduleConstructView');
        var data = temp.getData();


        var evnId = data.buildPack[0].id;


        var serviceIds = new Array();
        var tLen = 0;
        var i = 0;

        var serType1_len = data.serType1.length;
        var serType2_len = data.serType2.length;
        var serType3_len = data.serType3.length;


        for (i = 0; i < serType1_len; i++) {
            serviceIds[tLen++] = data.serType1[i].id;
        }
        for (i = 0; i < serType2_len; i++) {
            serviceIds[tLen++] = data.serType2[i].id;
        }
        for (i = 0; i < serType3_len; i++) {
            serviceIds[tLen++] = data.serType3[i].id;
        }

        tLen = serviceIds.length;
        var ids = '';
        for (i = 0; i < tLen; i++) {
            ids += serviceIds[i] + ',';
        }
        var form = new Ext.form.Basic(win, {});

        var appForm = win.down('form[itemId=appForm]');
        form.setValues(appForm.getValues());

        var orgName = 'admin';
        var space = 'admin';
        var domain = form.getValues().domain;
        var memory = form.getValues().memory;
        var instance = form.getValues().instance;
        var temName = form.getValues().temName;
        var isTemTipHidden = win.down('displayfield[itemId=errorTemEmpTip]').isHidden();
        if (domain == '') {
            win.down('displayfield[itemId=errorDomainEmpTip]').setVisible(true);
            return false;
        }
        if (memory == '') {
            win.down('displayfield[itemId=errorMemoryEmpTip]').setVisible(true);
            return false;
        }
        if (temName == '') {
            win.down('displayfield[itemId=errorTemEmpTip]').setValue(cfWebLang.CfWindow.temNameEmp);
            win.down('displayfield[itemId=errorTemEmpTip]').setVisible(true);
            return false;
        }
        if (isTemTipHidden == false) {
            return;
        } else {
            var isEdit = me.isEdit;
            var id = me.id;
            if (isEdit == true) {
                Ext.Ajax.request({
                    url: 'rest/template/edit?id=' + id + '&temName=' + temName + '&evnId=' + evnId +
                    '&serviceIds=' + ids + '&orgName=' + orgName
                    + '&spaceName=' + space + '&domain=' + domain + '&memeory='
                    + memory + '&disk=1024' + '&instance=' + instance,
                    method: 'GET',
                    success: function (resp) {
                        var obj = Ext.JSON.decode(resp.responseText);
                        if (!obj.success) {
                            Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.EditTemplateFailed);
                        }
                        store.load();
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.EditTemplateSuccess);
                        me.close();
                    },
                    failure: function (response) {
                        if (response.status == '401') {
                            Ext.Msg.show({
                                title: cfWebLang.Util.Tip,
                                id: 'firstWin',
                                msg: cfWebLang.Main.SessionOverdue,
                                width: 250,
                                buttons: Ext.MessageBox.OK,
                                fn: function () {
                                    parent.location.href = '/cfWeb/login.html';
                                },
                                cls: 'overtimeWin'
                            });
                            //Ext.WindowManager.bringToFront ('firstWin');
                            /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                             parent.location.href = '/cfWeb/login.html';
                             }); */
                            return;
                        }

                        if (response.timedout) {
                            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                            return;
                        }
                        Ext.MessageBox.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.EditTemplateFailed);
                    }
                });
            }
            if (isEdit == false) {
                Ext.Ajax.request({
                    url: 'rest/template/add?temName=' + temName + '&evnId=' + evnId +
                    '&serviceIds=' + ids + '&orgName=' + orgName
                    + '&spaceName=' + space + '&domain=' + domain + '&memeory='
                    + memory + '&disk=1024' + '&instance=' + instance,
                    method: 'GET',
                    success: function (resp) {
                        var obj = Ext.JSON.decode(resp.responseText);
                        if (!obj.success) {
                            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.CreateTemplateFailed);
                        }
                        store.load();
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.CreateTemplateSuccess);
                        me.close();
                    },
                    failure: function (response) {
                        if (response.status == '401') {
                            Ext.Msg.show({
                                title: cfWebLang.Util.Tip,
                                id: 'firstWin',
                                msg: cfWebLang.Main.SessionOverdue,
                                width: 250,
                                buttons: Ext.MessageBox.OK,
                                fn: function () {
                                    parent.location.href = '/cfWeb/login.html';
                                },
                                cls: 'overtimeWin'
                            });
                            //Ext.WindowManager.bringToFront ('firstWin');
                            /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                             parent.location.href = '/cfWeb/login.html';
                             }); */
                            return;
                        }

                        if (response.timedout) {
                            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                            return;
                        }
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.CreateTemplateFailed);
                    }
                });
            }
        }
    },

    load: function (me) {
        me.store.load();
    },

    itemsClick: function (me, record, e) {
        var insertType = me.insertType;
        var data = {};
        data.name = record.itemName;
        data.id = record.itemId;
        data.img = record.itemIco;
        var insert = {};
        insert[insertType] = data;

        var win = me.up('cfWindow');

        var temp = win.down('moduleConstructView');

        temp.addItem(insert);
    },

    nextTemplateView: function (me, oldIndex, newIndex) {
        var isEdit = me.isEdit;
        var win = me.down('moduleConstructView');
        var data = win.getData();

        var buildPack = '';
        var buildPack_len = data.buildPack.length;
        if (buildPack_len == 1) {
            buildPack += data.buildPack[0].name;
        }
        Ext.getCmp('appTextfield').setValue(buildPack);

        var serType1 = '';

        var serType1_len = data.serType1.length;
        var serDis1 = Ext.getCmp('storageTextfield');
        if (serType1_len > 0) {
            for (var i = 0; i < serType1_len; i++) {
                serType1 += data.serType1[i].name + ' ';
            }
            serDis1.setValue(serType1);
            serDis1.show();
        } else {
            serDis1.hide();
        }

        var serType2 = '';
        var serType2_len = data.serType2.length;
        var serDis2 = Ext.getCmp('analyseTextfield');
        if (serType2_len > 0) {
            for (var i = 0; i < serType2_len; i++) {
                serType2 += data.serType2[i].name + ' ';
            }
            serDis2.setValue(serType2);
            serDis2.show();
        } else {
            serDis2.hide();
        }

        var serType3 = '';
        var serType3_len = data.serType3.length;
        var serDis3 = Ext.getCmp('serviceTextfield');
        if (serType3_len > 0) {
            for (var i = 0; i < serType3_len; i++) {
                serType3 += data.serType3[i].name + ' ';
            }
            serDis3.setValue(serType3);
            serDis3.show();
        } else {
            serDis3.hide();
        }

        if (buildPack_len == 0) {
            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.ChoseBuildpack);
            return false;
        }

    },

    onStatusChange: function (me, actionName, e) {
        var self = this;
        var store = Ext.getCmp('temp').getStore();

        var appName = me.getValues().title;

        var data = {};

        if (actionName == 'stop') {

            Ext.Ajax.request({
                url: 'rest/app/stop' + '?appName=' + appName,
                method: 'GET',
                success: function (resp) {
                    store.load();
                    data.status = 'STOPPED';
                    Ext.Ajax.request({
                            url: 'rest/app/details',
                            method: 'GET',
                            params: {
                                appName: appName
                            },
                            success: function (response) {
                                var obj = Ext.JSON.decode(response.responseText);
                                me.updateAppStatus(obj);
                                me.up('appListDetailsView').down('cfPanelTypeI[itemId=appIns]').down('switchContentView').setValue(obj.instStatus);
                            },
                            failure: function (response) {
                                if (response.status == '401') {
                                    Ext.Msg.show({
                                        title: cfWebLang.Util.Tip,
                                        id: 'firstWin',
                                        msg: cfWebLang.Main.SessionOverdue,
                                        width: 250,
                                        buttons: Ext.MessageBox.OK,
                                        fn: function () {
                                            parent.location.href = '/cfWeb/login.html';
                                        },
                                        cls: 'overtimeWin'
                                    });
                                    //Ext.WindowManager.bringToFront ('firstWin');
                                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                                     parent.location.href = '/cfWeb/login.html';
                                     }); */
                                    return;
                                }

                                if (response.timedout) {
                                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                                    return;
                                }
                                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                            }
                        }
                    );
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                    }
                }
            });
        }
        if (actionName == 'restart') {
            Ext.Ajax.request({
                url: 'rest/app/reboot' + '?appName=' + appName,
                method: 'GET',
                success: function (resp) {

                    store.load();
                    data.status = 'STARTED';
                    me.updateAppStatus(data);
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateSuccess);
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                    }
                }
            });
        }
        if (actionName == 'start') {
            Ext.Ajax.request({
                url: 'rest/app/boot' + '?appName=' + appName,
                method: 'GET',
                success: function (resp) {
                    store.load();
                    data.status = 'STARTED';
                    Ext.Ajax.request({
                            url: 'rest/app/details',
                            method: 'GET',
                            params: {
                                appName: appName
                            },
                            success: function (response) {
                                console.log('change success');
                                var obj = Ext.JSON.decode(response.responseText);
                                me.updateAppStatus(obj);
                                if (taskChange != null) {
                                    Ext.TaskManager.stop(taskChange);
                                }
                                if (this.taskChart != null) {
                                    Ext.TaskManager.stop(this.taskChart);
                                }
                                me.up('appListDetailsView').down('cfPanelTypeI[itemId=appIns]').down('switchContentView').setValue(obj.instStatus);
                                var win = me.up('appListDetailsView');
                            },
                            failure: function () {
                                console.log('change failed');
                            }
                        }
                    );
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateSuccess);
                },
                failure: function (response) {
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                    } else {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                    }
                }
            });
        }

    },
    onDomainChange: function (me, data, act, e) {

        var appName = data.title;
        var domain = data.domain;
        var name = '';
        for (var i = 0; i < domain.length; i++) {
            name += domain[i] + ',';
        }
        Ext.Ajax.request({
            url: 'rest/app/updateDomain?appName=' + appName + '&domains=' + name,
            method: 'GET',
            success: function (resp) {
                //				Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Util.OperateSuccess);
            },
            failure: function (resp) {
                if (resp.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (resp.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var error = Ext.JSON.decode(resp.responseText);
                if (error.data != null && error.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                }
            }
        });
    },
    showLog: function (button) {
        isOperayion = 1;
        var appName = button.up('appListDetailsView').appName;
        var detailContainer = button.up('container#detailContainer');
        var win = Ext.widget('logFileWindow');
        win.appName = appName;
        var lth = detailContainer.items.items.length;
        for (var i = 0; i < lth; i++) {
            detailContainer.items.items[i].hide();
        }
        detailContainer.add(win);
    },
    logFwinRender: function (win) {
        isOperayion = 1;
        var appName = win.appName;
        var store = win.down('grid').getStore();
        var dt = new Date();
        var dtFrom = Ext.Date.format(dt, 'Y-m-d') + ' 00:00:00';
        var dtTo = Ext.Date.format(dt, 'Y-m-d') + ' 23:59:59';
        store.on('beforeload', function (store, options) {
            Ext.apply(store.proxy.extraParams, {
                appName: appName,
                from: dtFrom,
                to: dtTo
            });
        });
        store.load();
    },
    logFileSearch: function (btn) {
        var win = btn.up('logFileWindow');
        var appName = win.appName;
        var from = Ext.util.Format.date(win.down('datefield[name=from]').getValue(), 'Y-m-d H:i:s');
        var to = Ext.util.Format.date(win.down('datefield[name=to]').getValue(), 'Y-m-d H:i:s');
        if (from != '' && to != '' && from > to) {
            Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.CfWindow.StartTimeEndTime);
            return;
        }
        var key = win.down('textfield[name=logKey]').getValue();
        var store = win.down('grid').getStore();
        store.on('beforeload', function (store, options) {
            Ext.apply(store.proxy.extraParams, {
                appName: appName,
                from: from,
                to: to,
                key: key
            });
        });
        store.load();
    },
    downloadLogFile: function (grid, cell, row, col) {
        var win = grid.up('logFileWindow');
        var appName = win.appName;
        var store = grid.getStore();
        var fileName = store.getAt(row).get('fileName');
        window.location.href = 'rest/log/download?appName=' + appName + '&fileName=' + fileName;
    },
    updataGraph: function (index, view) {
        var mem = view.down('instanceChartType[itemId=memChart]');
        var disk = view.down('panel').down('instanceChartType[itemId=diskChart]');
        var cpu = view.down('panel').down('cpuChartType[itemId=cpuChart]');
        var storeMemChange = mem.getStore();
        var storeDiskChange = disk.getStore();
        var storeCpuChange = cpu.getStore();
        if (view.statusList[index] != 'RUNNING') {
            var tempData = [];
            for (var i = 0; i < 10; i++) {
                tempData.push({
                    date: Ext.Date.format(new Date(), 'Y-m-d H:m:s') + i,
                    value: 0
                });
            }
            storeMemChange.loadData(tempData);
            storeDiskChange.loadData(tempData);
            storeCpuChange.loadData(tempData);
            mem.updateTitle(0 + 'MB');
            disk.updateTitle(0 + 'MB');
            cpu.updateTitle(0 + '%');
        } else {
            storeMemChange.loadData(view.instData[index].mem);
            storeDiskChange.loadData(view.instData[index].disk);
            storeCpuChange.loadData(view.instData[index].cpu);
            //			console.log(view.instData);
            mem.updateTitle(view.instData[index].mem[9].data + 'MB');
            disk.updateTitle(view.instData[index].disk[9].data + 'MB');
            cpu.updateTitle(view.instData[index].cpu[9].data + '%');
        }
    },

    updateChartData: function (self, w, h, eOpts) {
        var view = self;
        var me = this;
        var index = view.nowIndex;
        var win = view.up('appListDetailsView');
        if (!win) {
            return;
        }
        if (view.statusList[index] != 'RUNNING') {
            me.updataGraph(index, view);
            setTimeout(function () {
                me.updateChartData(view);
            }, 500);
            return;
        }
        var appName = win.appName;
        Ext.Ajax.request({
            url: 'rest/app/monitor?appName=' + appName + '&index=' + index,
            method: 'GET',
            success: function (resp) {
                var obj = Ext.JSON.decode(resp.responseText);
                var usage = obj.usage;
                if (usage == null) {
                    setTimeout(function () {
                        me.updateChartData(view);
                    }, 500);
                    return;
                }

                var cpuNum = (usage.cpu * 100).toFixed(1);
                //			    console.log("usage:"+cpuNum);
                if (cpuNum > 100) {
                    cpuNum = 100;
                }
                var diskNum = (usage.disk / 1024 / 1024).toFixed(1);
                var memNum = (usage.mem / 1024 / 1024).toFixed(1);
                var diskNew = (usage.disk / obj.disk_quota * 100).toString();
                var diskPer = diskNew.substring(0, diskNew.indexOf('.') + 3);
                var memNew = (usage.mem / obj.mem_quota * 100).toString();
                var memPer = memNew.substring(0, memNew.indexOf('.') + 3);


                view.instData[index].cpu.shift();
                view.instData[index].mem.shift();
                view.instData[index].disk.shift();
                view.instData[index].cpu.push({
                    date: usage.time,
                    value: parseFloat(cpuNum),
                    data: cpuNum
                });
                view.instData[index].mem.push({
                    date: usage.time,
                    value: parseFloat(memPer),
                    data: memNum
                });
                view.instData[index].disk.push({
                    date: usage.time,
                    value: parseFloat(diskPer),
                    data: diskNum
                });
                me.updataGraph(index, view);
                setTimeout(function () {
                    me.updateChartData(view);
                }, 500);

            },
            failure: function (response) {
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                setTimeout(function () {
                    me.updateChartData(view);
                }, 1000);
            }
        });
    },
    appVarEnvRender: function (me) {
        var objSlide = me.up('slideLayer');
        var objHead = objSlide.down('appHeadView');
        var appName = objHead.ownerCt.appName;
        var store = me.getStore();
        store.load({
            params: {
                appName: appName
            }
        });
    },

    appVarEnvDelete: function (me, key, e) {
        var objSlide = me.up('slideLayer');
        var objHead = objSlide.down('appHeadView');
        var appName = objHead.ownerCt.appName;
        Ext.Ajax.request({
            url: 'rest/app/deleteEnv',
            method: 'GET',
            params: {
                appName: appName,
                key: key
            },
            success: function (resp) {
            },
            failure: function (response) {
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var error = Ext.JSON.decode(response.responseText);
                if (error.data != null && error.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                }
            }
        });
    },
    appVarEnvAdd: function (me, newKey, newValue) {
        console.log('hahahah');
        console.log(me);
        console.log(newKey);
        console.log(newValue);
        var objSlide = me.up('slideLayer');
        var objHead = objSlide.down('appHeadView');
        var appName = objHead.ownerCt.appName;
        var storeVarEnv = objSlide.down('variableListView').getStore();
        for (var i = 0; i < storeVarEnv.data.length; i++) {
            if (newKey == storeVarEnv.data.items[i].data.key) {
                Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Error.VarEnvNameRepeat);
                return false;
            }
        }
        Ext.Ajax.request({
            url: 'rest/app/addEnv',
            method: 'GET',
            params: {
                appName: appName,
                key: newKey,
                value: newValue
            },
            success: function (resp) {
                return true;
            },
            failure: function (response) {
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var error = Ext.JSON.decode(response.responseText);
                if (error.data != null && error.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                }
            }
        });
    },
    appVarEnvUpdate: function (me, oKey, newKey, newValue) {
        var objSlide = me.up('slideLayer');
        var objHead = objSlide.down('appHeadView');
        var appName = objHead.ownerCt.appName;
        Ext.Ajax.request({
            url: 'rest/app/modifyEnv',
            method: 'GET',
            params: {
                appName: appName,
                oldKey: oKey,
                newKey: newKey,
                value: newValue
            },
            success: function (resp) {
            },
            failure: function (response) {
                if (response.status == '401') {
                    Ext.Msg.show({
                        title: cfWebLang.Util.Tip,
                        id: 'firstWin',
                        msg: cfWebLang.Main.SessionOverdue,
                        width: 250,
                        buttons: Ext.MessageBox.OK,
                        fn: function () {
                            parent.location.href = '/cfWeb/login.html';
                        },
                        cls: 'overtimeWin'
                    });
                    //Ext.WindowManager.bringToFront ('firstWin');
                    /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                     parent.location.href = '/cfWeb/login.html';
                     }); */
                    return;
                }

                if (response.timedout) {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                    return;
                }
                var error = Ext.JSON.decode(response.responseText);
                if (error.data != null && error.data.source == 1) {
                    Ext.MessageBox.alert(cfWebLang.ErrorSource.cloudfoundry, error.data.message);
                } else {
                    Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.Util.OperateFailed);
                }
            }
        });
    },
    addDefaultService: function (me) {
        console.log(me);
        var win = Ext.widget('newDatabaseView', {
            title: me.title
        });
        var serviceBrokerStore = win.store;
        var brokers = me.brokers;
        win.prefix = me.prefix;
        win.serviceId = me.serviceId;
        win.viewStore = me.down('combobox').getStore();
        serviceBrokerStore.load({
            params: {
                lguid: brokers
            },
            callback: function (re) {
                serviceBrokerStore.loadData(re);
                win.down('form').down('combobox[itemId=serviceName]').setValue(serviceBrokerStore.getAt(0).get('label'));
                win.show();
            }
        });

    },

    addDatabaseService: function (me) {
        console.log(me.title);
        var win = Ext.widget('newDatabaseView');
        var serviceBrokerStore = win.store;
        win.viewStore = me.store;
        var dbStore = Ext.create('cfWeb.store.dataStorage.DatabaseTmpStore');
        dbStore.autoLoad = false;
        var serviceName = me.title;
        dbStore.load({
            callback: function (records) {
                var databaseBrokerStore = dbStore.data.items;
                var storeServiceName = win.down('container').down('form')
                    .down('combobox[itemId=serviceName]').getStore();
                if (serviceName != null) {
                    for (var i = 0; i < databaseBrokerStore.length; i++) {
                        if (databaseBrokerStore[i].data.itemName == serviceName) {
                            var prefix = databaseBrokerStore[i].data.serPrefix;
                            win.prefix = prefix;
                            win.serviceId = databaseBrokerStore[i].data.itemId;
                            var serviceBroker = databaseBrokerStore[i].data.brokers;
                            var brokers = null;
                            for (var j = 0; j < serviceBroker.length; j++) {
                                brokers = serviceBroker[j] + ',' + brokers;
                            }
                            serviceBrokerStore.load({
                                params: {
                                    lguid: brokers
                                },
                                callback: function (re) {
                                    storeServiceName.loadData(re);
                                    win.down('form').down('combobox[itemId=serviceName]')
                                        .setValue(storeServiceName.getAt(0).get('label'));
                                }
                            });
                        }
                    }
                    win.show();
                }
                if (me.up('newBindServiceWindow') != null) {
                    for (var i = 0; i < databaseBrokerStore.length; i++) {
                        var serName = me.up('newBindServiceWindow').down('combobox[itemId=serCombo]').getValue();
                        if (databaseBrokerStore[i].data.itemName == serName) {
                            var prefix = databaseBrokerStore[i].data.serPrefix;
                            win.prefix = prefix;
                            win.serviceId = databaseBrokerStore[i].data.itemId;
                            var serviceBroker = databaseBrokerStore[i].data.brokers;
                            var brokers = null;
                            for (var j = 0; j < serviceBroker.length; j++) {
                                brokers = serviceBroker[j] + ',' + brokers;
                            }
                            console.log(brokers);
                            serviceBrokerStore.load({
                                params: {
                                    lguid: brokers
                                },
                                callback: function (re) {
                                    storeServiceName.loadData(re);
                                    win.down('form').down('combobox[itemId=serviceName]')
                                        .setValue(storeServiceName.getAt(0).get('label'));
                                }
                            });
                        }
                    }
                    win.show();
                }
            }
        });
    },

    serviceNameChange: function (me) {
        var store = me.up('newDatabaseView').store;
        var service = me.getValue();
        var planStore = me.up('newDatabaseView').down('combobox[itemId=servicePlan]').getStore();
        planStore.loadData(store.findRecord('label', service).get('plans'));
    },

    createServices: function (me) {
        var serviceForm = me.down('form');
        var window = me;
        var publicValue = serviceForm.down('combobox[itemId=servicePlan]').getStore().getAt(0).get('public');
        var planId = serviceForm.down('combobox[itemId=servicePlan]').getStore().getAt(0).get('guid');
        console.log(me.serviceId);
        var serviceId = me.serviceId;
        if (Ext.getCmp('databaselist') == null) {
            var waitWindow = Ext.MessageBox.show({
                title: cfWebLang.Util.CreateApp,
                closable: false,
                cls: 'style-cfLoading'
            });
            var storeSelect = me.viewStore;
            Ext.Ajax.request({
                url: 'rest/service/createinstance',
                method: 'POST',
                params: {
                    service: serviceForm.getValues().service,
                    plan: serviceForm.getValues().plan,
                    planId: planId,
                    prefix: me.prefix,
                    visibility: publicValue,
                    typeId: me.serviceId
                },
                success: function (res) {
                    waitWindow.close();
                    window.close();
                    if (typeof (storeSelect) != 'undefined') {
                        storeSelect.load({
                            params: {
                                second: serviceId
                            },
                            callback: function (re) {
                                console.log(re);
                            }
                        });
                    }

                },
                failure: function (response) {
                    waitWindow.close();
                    if (typeof (storeSelect) != 'undefined') {
                        storeSelect.load({
                            params: {
                                second: serviceId
                            },
                            callback: function (re) {
                                console.log(re);
                            }
                        });
                    }
                    if (response.status == '401') {
                        Ext.Msg.show({
                            title: cfWebLang.Util.Tip,
                            id: 'firstWin',
                            msg: cfWebLang.Main.SessionOverdue,
                            width: 250,
                            buttons: Ext.MessageBox.OK,
                            fn: function () {
                                parent.location.href = '/cfWeb/login.html';
                            },
                            cls: 'overtimeWin'
                        });
                        //Ext.WindowManager.bringToFront ('firstWin');
                        /* Ext.Msg.alert(cfWebLang.Util.Tip,cfWebLang.Main.SessionOverdue, function(){
                         parent.location.href = '/cfWeb/login.html';
                         }); */
                        return;
                    }

                    if (response.timedout) {
                        Ext.Msg.alert(cfWebLang.Util.Tip, cfWebLang.global.timeout);
                        return;
                    }
                    var error = Ext.JSON.decode(response.responseText);
                    if (error.data != null && error.data.source == 1) {
                        Ext.MessageBox.show({
                            title: cfWebLang.ErrorSource.cloudfoundry,
                            msg: error.data.message,
                            cls: 'style-cfMessText',
                            buttons: Ext.MessageBox.OK
                        });
                    } else {
                        Ext.MessageBox.show({
                            title: cfWebLang.ErrorSource.app,
                            msg: cfWebLang.Error.SystemError,
                            cls: 'style-cfMessText',
                            buttons: Ext.MessageBox.OK
                        });
                    }
                }

            });
        }
    },
    isRefresh: function (me) {
        if (isOperayion == 1 && Ext.getCmp('temp') != null) {
            var store = Ext.getCmp('temp').getStore();
            console.log(store);
            store.load();
            isOperayion = 0;
        }
        if (typeof accesstimer != 'undefined' && accesstimer != null) {
            clearInterval(accesstimer);
        }

        if (typeof latencytimer != 'undefined' && latencytimer != null) {
            clearInterval(latencytimer);
        }
    },

    openAnalyLog: function (button) {
        var appName = button.up('appListDetailsView').appName;
        var appdetailWin = button.up('container#detailContainer');
        //		var appdetailWinH=appdetailWin.getHeight()-182;
        var win = Ext.widget('logAnalyWindow', {
            appName: appName
        });
        var lth = appdetailWin.items.items.length;
        for (var i = 0; i < lth; i++) {
            appdetailWin.items.items[i].hide();
        }
        appdetailWin.add(win);

        //		win.slideUp();
    }
});
